<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 乐视视频去重
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300010_000007_t_cms_article_unique_video extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%cms_article_video}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)
        ->groupBy(['article_id', 'le_id', 'le_unique'])
        ->having('count(*)>1');
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        foreach ($rows as $row) {
            $migration->delete($migration->tableName, [
                'and',
                ['!=', 'id', $row['id']],
                ['le_id' => $row['le_id']],
                ['article_id' => $row['article_id']],
                ['le_unique' => $row['le_unique']],
            ]);
        }
    }

}
